<template>
  <div class="page-controller">
    <el-container>
      <el-aside width="240px" class="tree_css">
        <h3>组织机构列表</h3>
        <FITree
          class="tree_box"
          :filter-node-method="filterNode"
          :showFilter="true"
          :showCheckbox="false"
          @nodeClick="nodeClick"
        ></FITree>
      </el-aside>
      <el-container>
        <el-main>
          <FISearchForm
            ref="ruleFormRef"
            :id="`inqu_${tableId}`"
            :searchNum="getHasSearchValues(state.query)"
            v-model:form-value="state.query"
            :table-column="columns"
            :wrapperSpan="searchWrapperSpan"
            @submit="searchFn"
          >
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem prop="loginName" label="登录账号">
                <FIInput v-model="state.query.loginName" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem name="userName" label="用户姓名">
                <FIInput v-model="state.query.userName" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem name="isLocked" label="是否锁定">
                <FISelect
                  v-model="state.query.isLocked"
                  valueCustom="value"
                  :options="[
                    { value: '1', label: '是' },
                    { value: '0', label: '否' },
                  ]"
                  clearable
                />
              </FIFormItem>
            </el-col>
          </FISearchForm>
          <div class="margin-bottom20"></div>

          <FITable
            ref="tableRef"
            class="box-radius2"
            title="账号列表"
            :id="`result_${tableId}`"
            :readonly="false"
            :insertable="false"
            :data="state.dataList"
            primaryKey="userId"
            v-model:columns="columns"
            :settingConfig="settingConfig"
            :isLoading="isTableLoading"
            :saveSuccessful="saveSuccessful"
            :pageConfig="pageConfig"
            @row-add-save="addRowSave"
            @table-refresh="searchFn"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-page-change="handleCurrentChange"
            @action-click="actionClick"
          >
            <template #headerBtn>
              <FIButton
                id="openRegist"
                class="margin-left5"
                border
                @click.stop="btnClick('register')"
              ></FIButton>
              <FIButton id="enable" class="margin-left5" border @click.stop="btnClick('open')"></FIButton>
              <FIButton
                id="disable"
                class="margin-left5"
                border
                @click.stop="btnClick('disable')"
              ></FIButton>
              <FIButton id="lock" class="margin-left5" border @click.stop="btnClick('lock')"></FIButton>
              <FIButton
                id="unlock"
                class="margin-left5"
                border
                @click.stop="btnClick('unlock')"
              ></FIButton>
              <FIButton
                id="openAlterDept"
                class="margin-left5"
                border
                @click.stop="btnClick('org')"
              ></FIButton>
              <FIButton
                id="export"
                class="margin-left5"
                border
                @click.stop="btnClick('export')"
              ></FIButton>
            </template>
          </FITable>
        </el-main>
      </el-container>
    </el-container>
    <register
      :modelValue="modelValue"
      @update:modelValue="(newValue) => (modelValue = newValue)"
      @get-list="searchFn"
    ></register>
    <FIModel v-model="orgVisible" width="500" title="变更组织机构">
      <FIFormItem label="所属组织机构">
        <!-- <FICascader @select-data="selectData"></FICascader> -->
        <FICascader-tree @select-node="selectNode" id="deptId"></FICascader-tree>
      </FIFormItem>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <FIButton id="alterDept" class="margin-left5" border @click="orgConfirm"></FIButton>
            <FIButton @click="orgVisible = false">取消</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
    <editInfo
      :editShow="editShow"
      @update:editShow="(newValue) => (editShow = newValue)"
      :editData="editData"
      @get-list="searchFn"
    ></editInfo>
    <assign-users
      :usersShow="usersShow"
      @update:usersShow="(newValue) => (usersShow = newValue)"
      :editData="editData"
    ></assign-users>
    <assign-post
      :postShow="postShow"
      @update:postShow="(newValue) => (postShow = newValue)"
      :editData="editData"
    ></assign-post>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import editInfo from './components/editInfo'
import assignUsers from './components/assignUsers'
import assignPost from './components/assignPost'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIForm from '@/components/FIForm.vue'
import FIModal from '@/components/FIModal.vue'
import FICascader from '@/components/FICascader.vue'
import FITree from '@/components/FITree.vue'
import register from './components/register'
import { apiRequestPost, apiRequestExport } from '@/api/globalApi.js'
import { apiLock, apiDisable, apiGetDeptTree, apiUnlock, apiResetPassword, apiExport, apialterDept } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData,getHasSearchValues } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const defaultProps = {
  children: 'subNodes',
  // label: 'payload.orgCname',
  label: (data) => data.payload.orgCname,
}
const searchWrapperSpan = 8
const showSearch = ref(true)
const orgVisible = ref(false)
const isTableLoading = ref(false)
const editShow = ref(false)
const usersShow = ref(false)
const postShow = ref(false)
// 页面编码
const tableId = 'userInfo'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const modelValue = ref(false)
const rawArray = ref([])
const orgSelect = reactive({
  label: '',
  value: '',
})
const settingConfig = reactive({
  export: false, // 隐藏导出
  setting: true, // 设置
  locked: true, // 锁定
  density: true, // 密度
  showSearch: true, // 是否显示绑定搜索表单
  refresh: true, // 是否显示刷新
  hidden: false, // 隐藏操作栏上所有内容
})
const state = reactive({
  query: {
    current: 1,
    size: 10,
    loginName: '',
    isLocked: '',
    userName: '',
    // deptEname:'',
    // deptId:''
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
const columns: Column[] = reactive([
  {
    label: '登录账号',
    prop: 'loginName',
    align: 'center',
    width: '120',
    // editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '用户姓名',
    prop: 'userName',
    align: 'center',
    width: '140',
    queryName: '',
    editable: false,
    sortable: false,
    filterable: false,
    readonly: true,
  },
  {
    label: '所属组织机构',
    prop: 'deptCname',
    align: 'center',
    width: '160',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '账号状态',
    prop: 'status',
    align: 'center',
    width: '120',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: false,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' },
      ],
    },
  },
  {
    label: '是否锁定',
    prop: 'isLocked',
    align: 'center',
    width: '100',
    editable: false,
    filterable: false,
    sortable: false,
    modelValue: { inputValue: '' },
    editType: 'select',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  {
    label: '性别',
    prop: 'gender',
    align: 'center',
    width: '100',
    filterable: false,
    modelValue: { inputValue: '' },
    editType: 'select',
    editConfig: {
      options: [
        { value: '1', label: '男' },
        { value: '0', label: '女' },
      ],
    },
  },
  {
    label: '手机号',
    prop: 'mobile',
    align: 'center',
    width: '150',
    filterable: false,
    sortable: false,
    editType: 'input',
  },
  {
    label: '密码过期时间',
    prop: 'pwdExpireDate',
    align: 'center',
    width: '130',
    editType: 'time-picker',
  },
  {
    label: '密码修改时间',
    prop: 'pwdReviseDate',
    align: 'center',
    width: '160',
    editable: false,
    filterable: false,
    sortable: false,
    editType: 'time-picker',
  },
  {
    label: '密码修改人',
    prop: 'pwdRevisor',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '电子邮件',
    prop: 'email',
    align: 'center',
    width: '160',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '工号',
    prop: 'jobNo',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '固定电话',
    prop: 'businessPhone',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '',
    prop: 'action',
    actionConfig: [
      { id: 'openUpdate', type: 'edit' },
      { id: 'openUGroup', type: 'users' },
      { id: 'openPost', type: 'post' },
      { id: 'resetPassword', type: 'password' },
    ],
  },
])

const checkedRows = ref([])
const editData = ref({})
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const treeObj = ref({})
const nodeClick = (val) => {
  console.log(val,'val123')
  treeObj.value = val
  // state.query.deptId = val.value
  // state.query.deptEname = val.orgEname,
  searchFn('query', '')
}
const selectNode = (val) => {
  orgSelect.value = val
}
const orgConfirm = () => {
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.userId) ids.push(item?.userId)
    })

  isTableLoading.value = true
  const par = {
    deptId: orgSelect.value,
    userIds: ids,
  }
  const apiUrl = proxy.$Button_api('alterDept', route.name)
  apiRequestPost(apiUrl, par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        orgVisible.value = false
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      useMessage().error(error.data.message)
    })
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  editData.value = JSON.parse(JSON.stringify(rowData))
  if (item.type == 'edit') {
    editShow.value = true
  } else if (item.type == 'users') {
    usersShow.value = true
  } else if (item.type == 'post') {
    postShow.value = true
  } else if (item.type == 'password') {
    ElMessageBox.confirm('此操作将重置密码，是否继续?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        const apiUrl = proxy.$Button_api('resetPassword', route.name)
        apiRequestPost(apiUrl, { loginName: rowData.loginName })
          .then((res) => {
            if (res.data.success) {
              useMessage().success(res.data.message)
            } else {
              useMessage().warning(res.data.message)
            }
          })
          .catch((err) => {
            useMessage().error(err.data.message)
          })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
  }
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    
    deptEname:treeObj.value.orgEname == 'root' ? '' : treeObj.value.orgEname,
    deptId:treeObj.value.value == 'root' ? '' : treeObj.value.value,
    ...state.query,
  }
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave(data, 'add')
}

//按钮事件
const btnClick = (type) => {
  if (type == 'register') {
    modelValue.value = true
    return;
  } 
  if (type == 'org') {
    // if(!treeObj.value.orgEname){
    //   useMessage().warning('请选择组织机构')
    //   return;
    // }
    if(!checkedRows.value.length){
      useMessage().warning('请选择一条数据')
      return;
    }
    orgVisible.value = true
    return;
  }
  if (type != 'export' && !checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  if (type == 'open') {
    const apiUrl = proxy.$Button_api('enable', route.name)
    apiFunc(apiUrl)
  } else if (type == 'disable') {
    const apiUrl = proxy.$Button_api('disable', route.name)
    apiFunc(apiUrl)
  } else if (type == 'lock') {
    const apiUrl = proxy.$Button_api('lock', route.name)
    apiFunc(apiUrl)
  } else if (type == 'unlock') {
    const apiUrl = proxy.$Button_api('unlock', route.name)
    apiFunc(apiUrl)
  } else if (type == 'export') {
    const apiUrl = proxy.$Button_api('export', route.name)
    apiRequestExport(apiUrl, state.query)
  }
}
const apiFunc = async (apiUrl) => {
  const par = checkedRows.value.map((v) => {
    return v.loginName
  })
  const { data } = await apiRequestPost(apiUrl, par)
  if (data.success) {
    useMessage().success(data.message)
    searchFn()
  }
}
watch(
  () => columns,
  (newValue) => {},
  { deep: true, immediate: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped>
@import '~@/assets/style/common.less';
/deep/ .el-main {
  padding-top: 0;
}
.tree_css {
  height: 100%;
  background: #ffffff;
  height: calc(100vh - 200px);
  .tree_box {
    padding: 0 12px;
  }
  h3 {
    font-size: 18px;
    line-height: 55px;
    padding-left: 15px;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
    color: #000000;
  }
}
</style>
